package com.comac.tasks.manager.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.comac.tasks.manager.app.api.TasksManagerService;
import com.comac.tasks.manager.app.domain.gateway.TasksManagerGateway;
import com.comac.tasks.manager.app.dto.*;
import com.comac.tasks.manager.app.feign.TasksManagerAppService;
import com.comac.tasks.manager.app.gatewayimpl.database.dataobject.PortalBacklogResult;
import com.comac.tasks.manager.app.gatewayimpl.database.dataobject.SingleBacklogDTO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;


/**
 * 流程代办controller
 *
 * @author wfb
 * @date 2021年12月15日18:07:15
 */
@RestController
@RequestMapping("/tasks")
@Slf4j
public class TasksManagerController implements TasksManagerAppService {
    @Autowired
    private TasksManagerService tasksManagerService;

    @Autowired
    private TasksManagerGateway tasksManagerGateway;

    @Override
    @Deprecated
    @ApiOperation(value = "代办组件插入接口")
    @RequestMapping(value = "/insertTasks", method = RequestMethod.POST)
    public Response insertTasks(@RequestBody TasksManagerDTO tasksManagerDTO) {
        return tasksManagerService.insertTasks(tasksManagerDTO);
    }

    @Override
    @ApiOperation(value = "代办组件批量插入接口")
    @RequestMapping(value = "/batchInsertTasks", method = RequestMethod.POST)
    public Response batchInsertTasks(@RequestBody TasksManagerBatchInsertDTO batchInsertDTO) {
        log.info("batchInsertDTO Request:" + JSONObject.toJSONString(batchInsertDTO));
        return tasksManagerService.batchInsertTasks(batchInsertDTO);
    }

    @Override
    @ApiOperation(value = "代办组件修改接口")
    @RequestMapping(value = "/updateTasks", method = RequestMethod.POST)
    public Response updateTasks(@RequestBody TasksManagerUpOperatorDTO upOperatorDTO) {
        log.info("upOperatorDTO Request:" + JSONObject.toJSONString(upOperatorDTO));
        if (CollectionUtil.isNotEmpty(upOperatorDTO.getProcessInstanceIds())
                || CollectionUtil.isNotEmpty(upOperatorDTO.getTaskInstanceIds())) {
            return tasksManagerService.updateTasks(upOperatorDTO);
        } else {
            return Response.buildFailure("10000002", "流程实例id和任务id都是空！");
        }
    }

    @Override
    @ApiOperation(value = "代办组件‘计划完成时间’更新接口")
    @RequestMapping(value = "/updateTasksExpectedCompletionTimeByTaskId", method = RequestMethod.POST)
    public Response updateTasksExpectedCompletionTimeByTaskId(@RequestBody TasksManagerUpECTimeDTO eCTimeUpdateDTO) {
        log.info("eCTimeUpdateDTO Request:" + JSONObject.toJSONString(eCTimeUpdateDTO));
        if (StringUtils.isNotBlank(eCTimeUpdateDTO.getTaskInstanceId()) &&
                StringUtils.isNotBlank(eCTimeUpdateDTO.getExpectedCompletionTime())) {
            return tasksManagerService.updateTasksECTime(eCTimeUpdateDTO);
        } else {
            return Response.buildFailure("10000002", "流程实例id 或 计划完成时间是空！");
        }
    }

    @Override
    @ApiOperation(value = "代办组件查询详情接口")
    @RequestMapping(value = "/listTasksDetails", method = RequestMethod.POST)
    public SingleResponse<TasksManagerVO> listTasksDetails(@RequestBody TasksManagerDetailsQry detailsQry) {
        log.info("detailsQry Request:" + JSONObject.toJSONString(detailsQry));
        return tasksManagerService.listTasksDetails(detailsQry);
    }

    @Override
    @ApiOperation(value = "代办组件查询列表接口")
    @RequestMapping(value = "/listTasks", method = RequestMethod.POST)
    public PageResponse<TasksManagerVO> listTasks(@RequestBody TasksManagerQry tasksManagerQry) {
        log.info("tasksManagerQry Request:" + JSONObject.toJSONString(tasksManagerQry));
        return tasksManagerService.listTasks(tasksManagerQry);
    }


    @Override
    @ApiOperation(value = "代办组件查询列表接口(我的申请)")
    @RequestMapping(value = "/listTasksByCreator", method = RequestMethod.POST)
    public PageResponse<TasksManagerVO> listTasksByCreator(@RequestBody TasksManagerQry tasksManagerQry) {
        log.info("tasksManagerQry Request:" + JSONObject.toJSONString(tasksManagerQry));
        return tasksManagerService.listTasksByCreator(tasksManagerQry);
    }

    @Override
    @ApiOperation(value = "代办组件变更状态接口")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public Response updateStatus(@RequestBody TasksManagerUpDTO tasksManagerUpDTO) {
        log.info("tasksManagerUpDTO Request:" + JSONObject.toJSONString(tasksManagerUpDTO));
        if (CollectionUtil.isNotEmpty(tasksManagerUpDTO.getProcessInstanceIds())
                || CollectionUtil.isNotEmpty(tasksManagerUpDTO.getTaskInstanceIds())) {
            return tasksManagerService.updateStatus(tasksManagerUpDTO);
        } else {
            return Response.buildFailure("10000002", "流程实例id和任务id都是空！");
        }
    }
    @Override
    @ApiOperation(value = "代办组件删除接口")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Response delete(@RequestBody TasksManagerDelDTO tasksManagerDelDTO) {
        log.info("tasksManagerDelDTO Request:" + JSONObject.toJSONString(tasksManagerDelDTO));
        if ("1".equals(tasksManagerDelDTO.getBusinessFlag())) {
            if (CollectionUtil.isNotEmpty(tasksManagerDelDTO.getProcessInstanceIds())
                    && StringUtils.isNotBlank(tasksManagerDelDTO.getCreator())) {
                return tasksManagerService.delete(tasksManagerDelDTO);
            } else {
                return Response.buildFailure("10000002", "流程实例id或创建人工号不存在！");
            }
        } else {
            if (CollectionUtil.isNotEmpty(tasksManagerDelDTO.getProcessInstanceIds())
                    || CollectionUtil.isNotEmpty(tasksManagerDelDTO.getTaskInstanceIds())) {
                return tasksManagerService.delete(tasksManagerDelDTO);
            } else {
                return Response.buildFailure("10000002", "流程实例id和任务id都是空！");
            }
        }
    }

    @ApiOperation(value = "商飞门户查询接口")
    @RequestMapping(value = "/findFrrBacklog", method = RequestMethod.GET)
    public void findFrrBacklog(HttpServletResponse response, String _callback, String num, String workno, String appCode) {
        log.info("findFrrBacklog() 入参:_callback = [{}],num = [{}],workno = [{}]", _callback, num, workno, appCode);
        PortalBacklogResult portalBacklogResult = new PortalBacklogResult();
        portalBacklogResult.setStat("false");
        String resultJson = null;
        try {
            if (StringUtils.isNotEmpty(workno)) {
                TasksManagerQry cmd = new TasksManagerQry();
                cmd.setPageNum(1);
                cmd.setOperator(workno);
                if (StringUtils.isNotEmpty(num)) {
                    cmd.setPageSize(Integer.parseInt(num));
                } else {
                    cmd.setPageSize(10);
                }
                cmd.setStatus("TODO");
                if (StringUtils.isNotBlank(appCode)) {
                    cmd.setSourceApplicationNum(appCode);
                }
                PageResponse<TasksManagerVO> pageResponse = tasksManagerService.listTasks(cmd);
                //查询成功
                if (pageResponse.isSuccess()) {
                    //加密用户工号
                    String str = Base64.getEncoder().encodeToString(workno.getBytes());
                    List<TasksManagerVO> data = pageResponse.getData();
                    List<SingleBacklogDTO> flowData = new ArrayList<>();
                    data.forEach((f) -> {
                        SingleBacklogDTO singleBacklogDTO = new SingleBacklogDTO();
                        singleBacklogDTO.setTitle(f.getNodeName() + "(" + f.getProcessName() + ")");
                        singleBacklogDTO.setPublishName(f.getCreatorName());
                        singleBacklogDTO.setPublishDate(DateUtil.format(f.getProcessCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        singleBacklogDTO.setUrl(f.getJumpConnection());
                        flowData.add(singleBacklogDTO);
                    });
                    //代办任务总条数
                    portalBacklogResult.setCount(Integer.parseInt(pageResponse.getTotalCount().toString()));
                    //代办任务集合
                    portalBacklogResult.setSize(portalBacklogResult.getSize());
                    portalBacklogResult.setFlowData(flowData);
                    portalBacklogResult.setStat("ok");
                    resultJson = JSON.toJSONString(portalBacklogResult);
                }
                response.setHeader("Content-Type", "text/html;charset=utf-8");
                response.getWriter().print(_callback + "(" + resultJson + ")");
            }
            log.info("resultJson reault:" + resultJson);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("findFrrBacklog() 发生异常", e);
            log.error("findFrrBacklog error msg:" + e.toString());
            log.error("findFrrBacklog stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("待办列表查询异常");
        }
    }

    @Override
    @ApiOperation(value = "更新待办任务类型 (针对历史数据）")
    @RequestMapping(value = "/updateTaskType", method = RequestMethod.POST)
    public Response updateTaskType(@RequestBody TasksManagerUpTaskTypeDTO tasksManagerUpTaskTypeDTO){
        log.info("updateTaskType Request:" + JSONObject.toJSONString(tasksManagerUpTaskTypeDTO));
        if (StringUtils.isNotEmpty(tasksManagerUpTaskTypeDTO.getProcessCode())
                || StringUtils.isNotEmpty(tasksManagerUpTaskTypeDTO.getNodeCode())) {
            return tasksManagerService.updateTaskType(tasksManagerUpTaskTypeDTO);
        } else {
            return Response.buildFailure("10000002", "流程模型编码与节点编码不能为空！");
        }
    }
}
